import { defineComponent, ref, onMounted, watch } from "vue";
import { getHotSingerListRequest, getSingerListRequest } from "../../api/api";
import { categoryTypes, alphaTypes } from '../../api/singer'
import { useRouter } from 'vue-router'
import ScrollRow from '../ScrollRow'
import Scroll from '../Scroll'
import './style.scss';

export default defineComponent({
  name: 'Singer',
  setup(props, context) {
    const isSearch = ref(false)
    const scrollRef = ref(null)
    const userList = ref([])
    const staticObj = {
      list: categoryTypes,
      list2: alphaTypes
    }
    const search = ref({
      category: '',
      alpha: ''
    })
    const count = ref(0)
    const router = useRouter()

    const enterDetail = (index) => {
      router.push(`/singer/detail/${index}`)
    }

    const rendUserList = () => userList.value.map((item) => (
      <li className="user-item" onClick={() => enterDetail(item.id)}>
        <div className="img">
          <img src={item.picUrl} alt=""/>
        </div>
        <span className="name">{ item.name }</span>
      </li>
    ))

    const requestCallback = (res) => {
      count.value = count.value + res.artists.length
      userList.value = [...userList.value, ...res.artists]
      scrollRef.value.refresh()
    }

    const getHotSingerList = () => {
      getHotSingerListRequest(count.value).then((res) => requestCallback(res))
    }

    const handlePullUp = () => {
      isSearch.value ? getSingerListByCount() : getHotSingerList()
    }

    const getSingerListByCount = () => {
      getSingerListRequest({ ...search.value, count: count.value }).then((res) => requestCallback(res))
    }

    onMounted(() => {
      getHotSingerList()
    })

    watch(search, () => {
      isSearch.value = true
      count.value = 0
      userList.value = []
      getSingerListByCount()
    }, { deep:true })

    return () => (
      <>
        <ScrollRow title="分类(默认热门):" handleClick={(key) => search.value.category = key} list={staticObj.list} />
        <ScrollRow title="首字母" handleClick={(key) => search.value.alpha = key.toLowerCase()} list={staticObj.list2} />
        <Scroll pullDown={true} handlePullUp={handlePullUp} scrollY={true} ref={scrollRef} height="calc(100% - 60px)">
          <ul className="user-list">
            { rendUserList() }
          </ul>
        </Scroll>
      </>
    )
  }
})